package dao

import (
	"database/sql"
	"errors"
	"fmt"
	"log"
)

type Customer struct {
	ID        int64  `json:"id"`
	Name      string `json:"name"`
	Token     string `json:"token"`
	CreatedAt string `json:"created_at"`
}

// 插入用户（存在：返回之前ID，不存在：插入并返回插入的ID）
func InsertCustomer(c Customer) (int64, error) {
	if db == nil {
		return 0, errors.New("db is nil")
	}

	query := "Select id from customer where name=?"
	row := db.QueryRow(query, c.Name)

	var id int64
	err := row.Scan(
		&id,
	)

	switch {
	case err == sql.ErrNoRows:
		res, err := db.Exec("INSERT INTO customer (name, token) VALUES (?, ?)", c.Name, c.Token)
		if err != nil {
			log.Fatal(err)
			return 0, err
		}
		id, _ = res.LastInsertId()
		log.Printf("Inserted customer success. customer:%v ID: %d", c, id)

		return id, nil
	case err != nil:
		return 0, fmt.Errorf("查询失败: %v", err)
	default:
		return id, nil
	}
}
